import json
import os
import sys

import requests

# 获取项目文件路径
current_dir = os.path.dirname(__file__)
# 提取项目根路径
root_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
# 将项目根路径存入，以便命令行运行时可以成功引包
sys.path.append(root_dir)

from FollowCourse.log import logger

username = 'fanchao@hongsong.club'
password = 'fanchao110'
# 获取当前文件路径，拼接json配置文件，生成路径，以供后面使用
path = os.path.dirname(__file__)
json_file_path = path + '/json.json'


# 获取最新的token，并替换文件中的token
def get_new_token():
    url = "https://crm.hongsong.info/gateway/api/fj-staff/account/v1/login"

    payload = json.dumps({
        "username": username,
        "password": password
    })
    headers = {
        'loginsource': 'crm',
        'priority': 'u=1, i',
        'token': '',
        'userid': '',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    token = response.json()['data']['token']

    # 读取token配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
    # 将获取到的接口的token，写入到data中
    data['token'] = token
    # 将data再次写入token文件，完成token的替换
    with open(json_file_path, 'w') as f1:
        f1.write(json.dumps(data))
    # print('token替换完成')
    logger.log_info('token替换完成')

    return str(token)


def get_token():
    # 读取token配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
        token = data['token']
    return str(token)


def write_today_live(today_live):
    """
    将今日的直播信息存到json.json中，程序出现问题。直接从里面调用直播间单独走监控消息的方法就行
    :param today_live: 直播信息
    :return: 无
    """
    # 读取配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
    # 将获取到直播信息，写入到data中
    data['today_live'] = today_live
    # 将data再次写入配置文件，完成替换
    with open(json_file_path, 'w') as f1:
        f1.write(json.dumps(data))
    logger.log_info('直播信息数据已写入完成')


def get_today_live():
    """
    从配置文件中获取今日直播信息
    :return: 返回今日直播信息
    """
    # 读取配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
    # 将获取到直播信息，写入到data中
    return data['today_live']


if __name__ == '__main__':
    print(get_token())
    print(get_token())
    print(get_token())
    print(get_token())
    print(get_token())
    print(get_token())

    print(get_new_token())
    print(get_new_token())
    print(get_token())
    print(get_token())

    write_today_live([1, 2])

    print(get_feishu_sign())

    print(get_feishu_sign())
